<script setup lang="ts">
import { useResizeObserver } from "@vueuse/core";
import { useRenderIcon } from "@/components/icon/src/hooks";
import { ref, computed, getCurrentInstance, onMounted } from "vue";
import enterOutlined from "@/assets/svg/enter_outlined.svg?component";
import Bookmark2Line from "@iconify-icons/ri/bookmark-2-line";
import { IMenu } from "@/core/pinia/interface";
import { useAppHooks } from "@/core/pinia/store/app.store";

interface Props {
  value: string;
  options: Array<IMenu>;
}

interface Emits {
  (e: "update:value", val: string): void;
  (e: "enter"): void;
}

const resultRef = ref();
const innerHeight = ref();
const props = withDefaults(defineProps<Props>(), {});
const emit = defineEmits<Emits>();
const instance = getCurrentInstance()!;
const app = useAppHooks();
const itemStyle = computed(() => {
  return (item: IMenu) => {
    return {
      background: item?.router === active.value ? app.getTheme.color : "",
      color: item.router === active.value ? "#fff" : "",
      fontSize: item.router === active.value ? "16px" : "14px"
    };
  };
});

const active = computed({
  get() {
    return props.value;
  },
  set(val: string) {
    emit("update:value", val);
  }
});

/** 鼠标移入 */
const handleMouse = async (item: IMenu) => {
  active.value = item.router;
};

const handleTo = () => {
  emit("enter");
};

const resizeResult = () => {
  // el-scrollbar max-height="calc(90vh - 140px)"
  innerHeight.value = window.innerHeight - window.innerHeight / 10 - 140;
};

useResizeObserver(resultRef, () => {
  resizeResult();
});

const handleScroll = (index: number) => {
  const curInstance = instance?.proxy?.$refs[`resultItemRef${index}`];
  if (!curInstance) return 0;
  const curRef = curInstance[0];
  const scrollTop = curRef.offsetTop + 128; // 128 两个result-item（56px+56px=112px）高度加上下margin（8px+8px=16px）
  return scrollTop > innerHeight.value ? scrollTop - innerHeight.value : 0;
};

onMounted(() => {
  resizeResult();
});

defineExpose({ handleScroll });
</script>

<template>
  <div ref="resultRef" class="result">
    <div
      v-for="(item, index) in options"
      :key="item.router"
      :ref="'resultItemRef' + index"
      class="result-item dark:bg-[#1d1d1d]"
      :style="itemStyle(item)"
      @click="handleTo"
      @mouseenter="handleMouse(item)"
    >
      <component :is="useRenderIcon(item.router ?? Bookmark2Line)" />
      <span class="result-item-title">{{ item.text }}</span>
      <enterOutlined />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.result {
  padding-bottom: 12px;

  &-item {
    display: flex;
    align-items: center;
    height: 56px;
    padding: 14px;
    margin-top: 8px;
    cursor: pointer;
    border: 0.1px solid #ccc;
    border-radius: 4px;
    transition: all 0.3s;

    &-title {
      display: flex;
      flex: 1;
      margin-left: 5px;
    }
  }
}
</style>
@/components/icon/src/hooks
